<?php
namespace app\admin\controller;
use think\Cookie;
use think\Cache;
use think\Db;

class Judge extends Common
{
    public function index()
    {
    	$data = model("judge")->getDataAll(1);
    	$this->assign('data',$data);

    	$major = Db::name('major')->where('status',1)->select();
		$this->assign('major',$major);

		$subject = Db::name('subject')->where('status',1)->select();
		$this->assign('subject',$subject);


        return $this->fetch();

    }

     //软删除
    public function del(){
    	//获取的是一个数组
    	$ids = input('post.ids/a');
    	//将数组转为字符串 以逗号分隔
    	$ids = implode(',',$ids);
    	//软删除 更新状态
    	$result = Db::name('judge')->where("id in ($ids)")->setField('status',0);
    	if($result){
    		$this->success("删除成功");
    	}else{
    		$this->error("删除失败");
    	}
    }
    // 二级联动
    public function major(){
    	$major_id = input('post.major_id');
    	$data = Db::name('subject')->where('major_id',$major_id)->select();
    	return json($data);
    } 

    public function add(){
        if (request()->isPost()) {
             $data = input('post.data/a');
             // dump($data);die;
             if(!$data){
                return json(array('code'=>0,'msg'=>"参数错误"));
             }
             $data['add_time'] = date('Y-m-d H:i:s');
             $result = model('Judge')->addJudge($data);

             if($result){
                    return json(['code'=>1,'msg'=>'添加成功']);
             }else{
                    return json(['code'=>0,'msg'=>'添加失败']);
             }


        }else{
            $major = Db::name('major')->where('status',1)->select();
            $this->assign('major',$major);

            $subject = Db::name('subject')->where('status',1)->select();
            $this->assign('subject',$subject);

            return $this->fetch();
        }
    
    }

    public function edit($id=""){
            if(request()->isPost()){
                $data = input('post.data/a');


                $result = Db::name('judge')->where('id',$data['id'])->update(['judge_name'=>$data['judge_name'],'right_key'=>$data['right_key'],'major_id'=>$data['major_id'],'subject_id'=>$data['subject_id']]);

                if ($result) {
                        return json(['code'=>1,'msg'=>'修改成功']);
                 }else{
                        return json(['code'=>0,'msg'=>'修改失败']);
                 }

            }else{
                $major = Db::name('major')->where('status',1)->select();
                $this->assign('major',$major);

                $subject = Db::name('subject')->where('status',1)->select();
                $this->assign('subject',$subject);

                $judge = model('judge')->editJudge($id);
                // dump($single);die;
                
                $this->assign('judge',$judge);


                $right_key = Db::name('judge')->select();
				$this->assign('right_key',$right_key);
				
                return $this->fetch();
            }

            
    }
}